//
//  HEHealthManageViewController.m
//  HealthFamily
//
//  Created by LOOK on 2020/12/20.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEHealthManageViewController.h"
#import "HEDataMangaeCell.h"
#import "HEOtherBindPhoneViewController.h"
#import "HEDataManageModel.h"
#import "HEHealthCheckDataController.h"
#import "BRStringPickerView.h"
#import "HEBindUserModel.h"

@interface HEHealthManageViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) UIButton *bottomView;

@property (nonatomic, strong) NSMutableArray <HEDataManageModel *> *dataSourceArr;

@property(nonatomic, strong) QMUIPopupMenuView *popupByWindow;

@property(nonatomic, strong) UIButton *addBtn;
@property(nonatomic, strong) HEDataManageModel *selectModel;

@property(nonatomic, strong) NSMutableArray <HEBindUserModel *> *bindUsers;
@property(nonatomic, strong) QMUIPopupMenuView *popUsersView;
@property(nonatomic, strong) UILabel *nameLb;
@property(nonatomic, strong) HEBindUserModel *selectUser;

@end

@implementation HEHealthManageViewController

- (NSMutableArray<HEBindUserModel *> *)bindUsers {
    if (!_bindUsers) {
        _bindUsers = @[].mutableCopy;
        UserInfo *user = [UserManager sharedUserManager].curUserInfo;
        HEBindUserModel *ower = [HEBindUserModel new];
        ower.id = user.id;
        ower.realname = user.realname;
        ower.relations = @"本人";
        [_bindUsers addObject:ower];
    }
    return _bindUsers;
}

- (NSMutableArray<HEDataManageModel *> *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"健康管理";
    _selectUser = self.bindUsers.firstObject;
    
    [self initUI];
    [self getBindUserData];
    [self loadData];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleViewClick)];
    [self.zx_navTitleView addGestureRecognizer:tap];
}

- (void)titleViewClick {
    [self.popUsersView showWithAnimated:YES];
}

#pragma mark - load data
- (void)getBindUserData {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:[UserManager sharedUserManager].curUserInfo.id forKey:@"gid"];
    
    KWeakSelf
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KgetBindUser parameters:dict success:^(id  _Nonnull responseObject) {
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        [weakSelf.bindUsers addObjectsFromArray:[HEBindUserModel mj_objectArrayWithKeyValuesArray:response.data]];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)loadData {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:_selectUser.id forKey:@"usid"];
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KHealthCheckValue parameters:dict success:^(id  _Nonnull responseObject) {
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        
        [self.dataSourceArr removeAllObjects];
        [self.dataSourceArr addObjectsFromArray:[HEDataManageModel mj_objectArrayWithKeyValuesArray:response.data]];

        [self popupByWindow];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];

     } failure:^(NSError * _Nonnull error) {
         [self.tableView.mj_header endRefreshing];
    }];
}

- (void)initUI {
   _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStylePlain];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    
   _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
   _tableView.scrollsToTop = YES;
   _tableView.tableFooterView = [[UIView alloc] init];
    
    [_tableView registerClass:HEDataMangaeCell.class forCellReuseIdentifier: @"HEDataMangaeCell"];
   
   self.tableView.backgroundColor = KWhiteColor;
   self.tableView.delegate = self;
   self.tableView.dataSource = self;
   [self.view addSubview:self.tableView];
    
    __weak __typeof(&*self)weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.isFromHeadRefresh = YES;
        [weakSelf loadData];
    }];
    
    
    // 标题栏
    UIView *titleView = [UIView new];
    
    UILabel *nameLb = [UILabel new];
    nameLb.text = @"健康管理(本人)";
    nameLb.font = DYFont(17);
    _nameLb = nameLb;
    [titleView addSubview:nameLb];
    
    UIImageView *arrowIcon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"down_arrow")];
    [titleView addSubview:arrowIcon];
    
    [nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(titleView);
        make.top.bottom.equalTo(titleView);
    }];
    [arrowIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleView);
        make.width.mas_equalTo(12);
        make.height.mas_equalTo(12);
        make.left.equalTo(nameLb.mas_right).offset(5);
    }];
    
    [self zx_addCustomTitleView:titleView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleViewClick)];
    [titleView addGestureRecognizer:tap];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HEDataMangaeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HEDataMangaeCell"];
    [cell configCellWithModel:_dataSourceArr[indexPath.row]];
   return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
 
   return [tableView fd_heightForCellWithIdentifier: @"HEDataMangaeCell" cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
       [cell configCellWithModel:self.dataSourceArr[indexPath.row]];
   }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HEDataManageModel *model = _dataSourceArr[indexPath.row];
    HEHealthCheckDataController *vc = [HEHealthCheckDataController new];
    vc.dataSourceArr = _dataSourceArr;
    vc.selectUser = _selectUser;
    vc.bindUsers = self.bindUsers;
    vc.index = indexPath.row;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = CViewBgColor;
    
    UILabel *_titleLb = [UILabel new];
    _titleLb.text = @"录入最新数据";
    _titleLb.font = DYFont(16);
    _titleLb.textColor = CNavLightBlackColor;
    [v addSubview:_titleLb];
     
    [v addSubview:self.addBtn];
    [self.addBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(v);
        make.right.equalTo(v).mas_offset(-10);
        make.width.height.mas_offset(26);
    }];
    
    [_titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(v).mas_offset(0);
        make.left.equalTo(v).mas_offset(10);
        make.right.equalTo(v).mas_offset(-10);
        make.bottom.equalTo(v).mas_offset(-0);
    }];
    
    return v;
}

- (UIButton *)addBtn {
    if (!_addBtn) {
        UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [addBtn setImage:IMAGE_NAMED(@"add") forState:UIControlStateNormal];
        [addBtn setTarget:self action:@selector(addClick) forControlEvents:UIControlEventTouchUpInside];
        _addBtn = addBtn;
    }
    return _addBtn;
}

- (QMUIPopupMenuView *)popupByWindow {
    if (!_popupByWindow) {
        
        
        // 使用方法 2，以 UIWindow 的形式显示到界面上，这种无需默认隐藏，也无需 add 到某个 UIView 上
        self.popupByWindow = [[QMUIPopupMenuView alloc] init];
        self.popupByWindow.automaticallyHidesWhenUserTap = YES;// 点击空白地方消失浮层
        self.popupByWindow.itemTitleColor = CNavLightBlackColor;
        self.popupByWindow.maskViewBackgroundColor = [KWhiteColor colorWithAlphaComponent:0.2];// 使用方法 2 并且打开了 automaticallyHidesWhenUserTap 的情况下，可以修改背景遮罩的颜色
        self.popupByWindow.shouldShowItemSeparator = YES;
        
        self.popupByWindow.itemConfigurationHandler = ^(QMUIPopupMenuView *aMenuView, QMUIPopupMenuButtonItem *aItem, NSInteger section, NSInteger index) {
            // 利用 itemConfigurationHandler 批量设置所有 item 的样式
            aItem.button.highlightedBackgroundColor = [KWhiteColor colorWithAlphaComponent:0.2];
        };
        KWeakSelf
        NSMutableArray *items = @[].mutableCopy;
        for (HEDataManageModel *model in self.dataSourceArr) {
            if ([@"BMI" isEqualToString:model.check_name]) {
                continue;
            }
            
            QMUIPopupMenuButtonItem *item = [QMUIPopupMenuButtonItem itemWithImage:nil title: model.check_name handler:^(QMUIPopupMenuButtonItem *aItem) {
                [aItem.menuView hideWithAnimated:YES completion:^(BOOL finished) {
                    for (HEDataManageModel *dataModel in self.dataSourceArr) {
                        if ([aItem.title isEqualToString:dataModel.check_name]) {
                            weakSelf.selectModel = dataModel;
                            [weakSelf submit];
                            break;
                        }
                    }
                }];
            }];
            [items addObject:item];
        }
        
        self.popupByWindow.items = items;
        self.popupByWindow.didHideBlock = ^(BOOL hidesByUserTap) {
            
        };
        self.popupByWindow.sourceView = self.addBtn;// 相对于 button4 布局
    }
    return _popupByWindow;
}

- (QMUIPopupMenuView *)popUsersView {
    if (!_popUsersView) {
         
        // 使用方法 2，以 UIWindow 的形式显示到界面上，这种无需默认隐藏，也无需 add 到某个 UIView 上
        _popUsersView = [[QMUIPopupMenuView alloc] init];
        _popUsersView.automaticallyHidesWhenUserTap = YES;// 点击空白地方消失浮层
        _popUsersView.itemTitleColor = CNavLightBlackColor;
        _popUsersView.maskViewBackgroundColor = [KWhiteColor colorWithAlphaComponent:0.2];// 使用方法 2 并且打开了 automaticallyHidesWhenUserTap 的情况下，可以修改背景遮罩的颜色
        _popUsersView.shouldShowItemSeparator = YES;
        _popUsersView.itemConfigurationHandler = ^(QMUIPopupMenuView *aMenuView, QMUIPopupMenuButtonItem *aItem, NSInteger section, NSInteger index) {
            // 利用 itemConfigurationHandler 批量设置所有 item 的样式
            aItem.button.highlightedBackgroundColor = [KWhiteColor colorWithAlphaComponent:0.2];
        };
        KWeakSelf
        NSMutableArray *items = @[].mutableCopy;
        for (HEBindUserModel *model in self.bindUsers) {
            QMUIPopupMenuButtonItem *item = [QMUIPopupMenuButtonItem itemWithImage:nil title: [NSString stringWithFormat:@"%@（%@）",model.realname, model.relations] handler:^(QMUIPopupMenuButtonItem *aItem) {
                [aItem.menuView hideWithAnimated:YES completion:^(BOOL finished) {
                    weakSelf.nameLb.text = [NSString stringWithFormat:@"健康管理(%@)", model.realname];
                    weakSelf.selectUser = model;
                    [weakSelf.tableView.mj_header beginRefreshing];
                }];
            }];
            [items addObject:item];
        }
        
        _popUsersView.items = items;
        _popUsersView.didHideBlock = ^(BOOL hidesByUserTap) {
            
        };
        _popUsersView.sourceView = self.zx_navTitleView;// 相对于 button4 布局
    }
    return _popUsersView;
}




- (void)addClick {
    [self.popupByWindow showWithAnimated:YES];
}
 
- (void)submit {
    // 性别
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc]init];
    stringPickerView.pickerMode = BRStringPickerComponentMulti;
    stringPickerView.title = self.selectModel.check_name;
    stringPickerView.dataSourceArr = [self getPickerData];
    stringPickerView.selectValues = [self getPickerDefualtVal];
    
    KWeakSelf
    stringPickerView.resultModelArrayBlock = ^(NSArray<BRResultModel *> * _Nullable resultModelArr) {
        NSString *value = @"";
        if (resultModelArr.count == 1) {
            BRResultModel *model = resultModelArr.firstObject;
            NSArray *strs = [model.value componentsSeparatedByString:weakSelf.selectModel.check_unit];
            value = strs.firstObject;
        }
        else {
            BRResultModel *model1 = resultModelArr[0];
            BRResultModel *model2 = resultModelArr[1];
            BRResultModel *model3 = resultModelArr[2];

            NSArray *strs1 = [model1.value componentsSeparatedByString:weakSelf.selectModel.check_unit];
            NSArray *strs3 = [model3.value componentsSeparatedByString:weakSelf.selectModel.check_unit];

            value = [NSString stringWithFormat:@"%@%@%@", strs1.firstObject, model2.value, strs3.firstObject];
        }
        
        [weakSelf saveCheckValue: value];
    };
    
    // 自定义弹框样式
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:CNavBgColor];
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}

- (void)saveCheckValue:(NSString *)val {
    
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:val forKey:@"check_value"];
    [params setValue:self.selectModel.check_code forKey:@"check_code"];
    [params setValue:self.selectModel.check_name forKey:@"check_name"];
    [params setValue:self.selectUser.id forKey:@"usid"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KHealthSave parameters:params success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"操作成功"];
        }
        [self.tableView.mj_header beginRefreshing];
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (NSArray *)getPickerData {
    
    NSInteger min = 0;
    NSInteger max = 0;
    NSMutableArray *data = @[].mutableCopy;
    BOOL isOne = NO;

    if ([@"身高" isEqualToString:_selectModel.check_name]) {
        min = 90;
        max = 250;
        isOne = YES;
    }
    else if ([@"体重" isEqualToString:_selectModel.check_name]) {
        min = 20;
        max = 150;
        isOne = YES;
    }
    else if ([@"睡眠" isEqualToString:_selectModel.check_name]) {
        min = 0;
        max = 24;
        isOne = YES;
    }
    else if ([@"呼吸次数" isEqualToString:_selectModel.check_name]) {
        min = 10;
        max = 60;
        isOne = YES;
    }
    else if ([@"血氧" isEqualToString:_selectModel.check_name]) {
        min = 50;
        max = 150;
        isOne = YES;
    }
    else if ([@"静息心率" isEqualToString:_selectModel.check_name]) {
        min = 30;
        max = 220;
        isOne = YES;
    }
    
    if (isOne) {
        NSMutableArray *vals = @[].mutableCopy;
        for (NSInteger i = min; i <= max; i++) {
            [vals addObject:[NSString stringWithFormat:@"%ld%@", i, _selectModel.check_unit]];
        }
        [data addObject:vals];
    }
    
    if ([@"体温" isEqualToString:_selectModel.check_name]) {
       min = 34;
       max = 43;
       
       NSMutableArray *vals1 = @[].mutableCopy;
       NSMutableArray *vals2 = @[].mutableCopy;
       NSMutableArray *vals3 = @[].mutableCopy;

       for (NSInteger i = min; i <= max; i++) {
           [vals1 addObject:[NSString stringWithFormat:@"%ld", i]];
       }
       [vals2 addObject:@"."];
       for (NSInteger i = 0; i <= 9; i++) {
           [vals3 addObject:[NSString stringWithFormat:@"%ld%@", i, _selectModel.check_unit]];
       }

       [data addObject:vals1];
       [data addObject:vals2];
       [data addObject:vals3];
   }
    else if ([@"血压" isEqualToString:_selectModel.check_name]) {
        min = 30;
        max = 150;
        
        NSMutableArray *vals1 = @[].mutableCopy;
        NSMutableArray *vals2 = @[].mutableCopy;
        NSMutableArray *vals3 = @[].mutableCopy;

        for (NSInteger i = min; i <= max; i++) {
            [vals1 addObject:[NSString stringWithFormat:@"%ld%@", i, _selectModel.check_unit]];
        }
        [vals2 addObject:@"/"];
        for (NSInteger i = 50; i <= 250; i++) {
            [vals3 addObject:[NSString stringWithFormat:@"%ld%@", i, _selectModel.check_unit]];
        }

        [data addObject:vals1];
        [data addObject:vals2];
        [data addObject:vals3];
    }
    else if ([@"血糖" isEqualToString:_selectModel.check_name]) {
        min = 0;
        max = 25;
        
        NSMutableArray *vals1 = @[].mutableCopy;
        NSMutableArray *vals2 = @[].mutableCopy;
        NSMutableArray *vals3 = @[].mutableCopy;

        for (NSInteger i = min; i <= max; i++) {
            [vals1 addObject:[NSString stringWithFormat:@"%ld", i]];
        }
        [vals2 addObject:@"."];
        for (NSInteger i = 0; i <= 9; i++) {
            [vals3 addObject:[NSString stringWithFormat:@"%ld%@", i, _selectModel.check_unit]];
        }

        [data addObject:vals1];
        [data addObject:vals2];
        [data addObject:vals3];
    }
    return data;
}

- (NSArray *)getPickerDefualtVal {
    if ([@"身高" isEqualToString:_selectModel.check_name]) {
        return @[[NSString stringWithFormat:@"175%@", _selectModel.check_unit]];
    }
    else if ([@"体重" isEqualToString:_selectModel.check_name]) {
        return @[[NSString stringWithFormat:@"65%@", _selectModel.check_unit]];
    }
    else if ([@"体温" isEqualToString:_selectModel.check_name]) {
        return @[@"36", @"." ,[NSString stringWithFormat:@"5%@", _selectModel.check_unit]];
    }
    else if ([@"睡眠" isEqualToString:_selectModel.check_name]) {
        return @[[NSString stringWithFormat:@"8%@", _selectModel.check_unit]];
    }
    else if ([@"血压" isEqualToString:_selectModel.check_name]) {
        return @[[NSString stringWithFormat:@"70%@", _selectModel.check_unit], @"/", [NSString stringWithFormat:@"120%@", _selectModel.check_unit]];
    }
    else if ([@"血糖" isEqualToString:_selectModel.check_name]) {
        return @[@"7", @"." ,[NSString stringWithFormat:@"0%@", _selectModel.check_unit]];
    }
    else if ([@"呼吸次数" isEqualToString:_selectModel.check_name]) {
        return @[[NSString stringWithFormat:@"20%@", _selectModel.check_unit]];
    }
    else if ([@"血氧" isEqualToString:_selectModel.check_name]) {
        return @[[NSString stringWithFormat:@"95%@", _selectModel.check_unit]];
    }
    else if ([@"静息心率" isEqualToString:_selectModel.check_name]) {
        return @[[NSString stringWithFormat:@"60%@", _selectModel.check_unit]];
    }
    return @[];
}

@end
 
